<script setup>

</script>

<template>
  <div class="app-container">
    <!-- 标题部分 -->
    <div class="page-header">
      <div class="header-title">
        <i class="el-icon-star-on"></i>
        <span>我的收藏商品</span>
      </div>
      <div class="header-desc">浏览您收藏的商品，快速下单采购</div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            prefix-icon="el-icon-goods"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入供应商"
            clearable
            prefix-icon="el-icon-office-building"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="商品类型" prop="type">
          <el-cascader
            v-model="queryParams.type"
            :options="typeTreeData"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'hover'
            }"
            placeholder="请选择商品类型"
            clearable
            filterable
            @change="val => console.log('选择的类型ID:', val)"
          ></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表展示 -->
    <el-card class="product-list-card" v-loading="loading">
      <div slot="header" class="card-header">
        <span>收藏商品列表</span>
        <div class="header-actions">
          <el-dropdown>
            <el-button type="text" icon="el-icon-sort">
              排序方式<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>价格从低到高</el-dropdown-item>
              <el-dropdown-item>价格从高到低</el-dropdown-item>
              <el-dropdown-item>最新收藏</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <div class="products-container">
        <el-row :gutter="20">
          <el-col
            :xs="12"
            :sm="8"
            :md="6"
            :lg="4"
            :xl="4"
            v-for="item in productListList"
            :key="item.id"
            class="product-col"
          >
            <div class="product-card" @click="viewProduct(item)">
              <div class="product-image">
                <img
                  :src="item.imageUrl || defaultImage"
                  :onerror="handleImageError"
                  alt="商品图片"
                />
                <div class="product-tags">
                  <el-tag size="mini" type="danger">
                    <i class="el-icon-star-on"></i> 已收藏
                  </el-tag>
                </div>
              </div>
              <div class="product-info">
                <div class="product-title" :title="item.name">{{ item.name }}</div>
                <div class="product-meta">
                  <span class="product-type" v-if="item.type">
                    {{ getTypeName(item.type) }}
                  </span>
                  <span class="product-supplier" v-if="item.supplierName">{{ item.supplierName }}</span>
                </div>
                <div class="bottom-info">
                  <span class="product-price">¥{{ item.unitPrice }}</span>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    circle
                    @click.stop="cancelCollection(item.id)"
                  ></el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 无数据提示 -->
        <div class="empty-block" v-if="!loading && productListList.length === 0">
          <i class="el-icon-star-off"></i>
          <span>您还没有收藏商品</span>
          <el-button type="primary" size="small" @click="goToProductList">去浏览商品</el-button>
        </div>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[12, 20, 30, 40]"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { fetchCategoryTree } from "@/api/official";
import defaultImage from '@/assets/images/product1.jpg'; // 导入默认图片
import request from '@/utils/request';

// 获取收藏商品列表API方法
function getBookmarkList(query) {
  return request({
    url: '/supply/book',
    method: 'get',
    data: query
  });
}

// 收藏/取消收藏API方法
function toggleBookmark(id) {
  return request({
    url: `/supply/book/${id}`,
    method: 'put'
  });
}

export default {
  name: "BookmarkList",
  dicts: ['product_type', 'product_status'],
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      productListList: [],
      defaultImage: defaultImage, // 添加默认图片
      handleImageError: 'this.src="' + defaultImage + '"', // 图片加载失败时的处理
      // 商品类型树数据
      typeTreeData: [],
      // 第三级商品类型列表
      thirdLevelTypes: [],
      queryParams: {
        pageNum: 1,
        pageSize: 12, // 每页显示数量改为12个
        name: null,
        type: null,
        status: 1,
        supplierId: null,
        supplierName: null
      },
    };
  },
  created() {
    this.getTypeTree();
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      getBookmarkList(this.queryParams).then(response => {
        this.productListList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取收藏商品列表失败:", error);
        this.$message.error("获取收藏商品列表失败");
        this.loading = false;
      });
    },
    // 获取商品类型树
    getTypeTree() {
      console.log('调用TypeTree接口获取商品类型');

      // 使用硬编码的商品类型数据，确保有基本数据显示
      const staticTypeData = [
        {
          id: 1,
          name: '备品备件',
          children: [
            { id: 4, name: '工厂自动化' },
            { id: 28, name: '低压配电' },
            { id: 36, name: '气动液压' },
            { id: 65, name: '动力传动' },
            { id: 76, name: '电线电缆' }
          ]
        },
        {
          id: 357,
          name: '办公用品',
          children: [
            { id: 358, name: '文具' },
            { id: 359, name: '办公设备' }
          ]
        },
        {
          id: 373,
          name: '百货个护',
          children: [
            { id: 374, name: '家居装饰' },
            { id: 375, name: '美妆护肤' },
            { id: 376, name: '小家电' },
            { id: 377, name: '个人护理' },
            { id: 378, name: '家用百货' }
          ]
        }
      ];

      // 初始使用静态数据
      this.typeTreeData = staticTypeData;

      // 提取所有类型到列表
      this.extractThirdLevelTypes(this.typeTreeData);

      // 从API获取真实数据
      fetchCategoryTree().then(response => {
        try {
          // 获取API返回的数据
          const rawData = response.data || response;

          // 使用专门的处理函数处理TypeTree格式的数据
          const processedTypeTree = this.processTypeTreeData(rawData);

          // 如果成功处理出数据，则更新本地数据
          if (processedTypeTree && processedTypeTree.length > 0) {
            this.typeTreeData = processedTypeTree;

            // 更新分类列表
            this.extractThirdLevelTypes(this.typeTreeData);
          }
        } catch (error) {
          console.error('处理API返回数据出错:', error);
        }
      }).catch(error => {
        console.error('调用TypeTree API失败:', error);
      });
    },
    /** 从类型树数据中提取所有层级类型 */
    extractThirdLevelTypes(treeData) {
      this.thirdLevelTypes = [];

      if (!treeData || treeData.length === 0) return;

      // 递归提取所有层级的类型
      const extractAllLevels = (nodes, parentPath = '') => {
        if (!nodes || !Array.isArray(nodes)) return;

        nodes.forEach(node => {
          if (!node) return;

          const id = typeof node.id === 'string' ? parseInt(node.id, 10) : (node.id || 0);
          const name = node.name || node.label || '未命名类型';
          const fullPath = parentPath ? `${parentPath} > ${name}` : name;

          // 添加当前节点到类型列表
          this.thirdLevelTypes.push({
            id: id,
            name: name,
            fullPath: fullPath
          });

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            extractAllLevels(node.children, fullPath);
          }
        });
      };

      // 开始递归处理
      extractAllLevels(treeData);

      // 确保至少有一条数据
      if (this.thirdLevelTypes.length === 0) {
        this.thirdLevelTypes.push({
          id: 0,
          name: '默认类型',
          fullPath: '默认类型'
        });
      }
    },
    /** 处理类型树数据，确保结构正确 */
    processTypeTreeData(rawData) {
      // 检查数据是否有效
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        return null;
      }

      // 创建处理结果数组 - 存储一级类目
      let processedData = [];

      // 遍历每一个一级类目项
      rawData.forEach(item => {
        if (!item || !item.firstCatalog) return;

        // 获取一级类目信息
        const firstCatalog = item.firstCatalog;

        // 创建一级类目节点
        const level1Node = {
          id: firstCatalog.id,
          name: firstCatalog.name,
          children: []
        };

        // 处理二级类目 - 来自childrenCatalog数组
        if (item.childrenCatalog && Array.isArray(item.childrenCatalog)) {
          // 只处理与当前一级类目关联的二级类目
          const level2Items = item.childrenCatalog.filter(l2 =>
            l2.parentId === firstCatalog.id ||
            l2.level === 2
          );

          level2Items.forEach(level2Item => {
            // 创建二级类目节点
            const level2Node = {
              id: level2Item.id,
              name: level2Item.name,
              children: []
            };

            // 处理三级类目 - 通常在二级类目的children中
            if (level2Item.children && Array.isArray(level2Item.children)) {
              // 筛选出确实是三级的项目
              const level3Items = level2Item.children.filter(l3 =>
                l3.parentId === level2Item.id ||
                l3.level === 3
              );

              level3Items.forEach(level3Item => {
                // 添加三级类目节点
                level2Node.children.push({
                  id: level3Item.id,
                  name: level3Item.name
                });
              });
            }

            // 只有当有三级节点时才保留children属性
            if (level2Node.children.length === 0) {
              delete level2Node.children;
            }

            // 添加二级节点到一级节点的children中
            level1Node.children.push(level2Node);
          });
        }

        // 只有当有二级节点时才保留children属性
        if (level1Node.children.length === 0) {
          delete level1Node.children;
        }

        // 添加一级节点到结果数组
        processedData.push(level1Node);
      });

      return processedData.length > 0 ? processedData : null;
    },
    /** 根据类型ID获取类型名称 */
    getTypeName(typeId) {
      if (typeId === undefined || typeId === null) return '未知类型';

      // 转换ID类型，便于多种匹配方式
      const typeStr = String(typeId);
      let typeNum = Number(typeId);
      if (isNaN(typeNum)) typeNum = 0;

      // 尝试在提取的类型列表中查找
      const matchingType = this.thirdLevelTypes.find(t =>
        t.id === typeId ||             // 完全匹配
        t.id === typeNum ||            // 数字类型匹配
        String(t.id) === typeStr       // 字符串匹配
      );

      // 如果找到匹配，返回类型名称
      if (matchingType) {
        return matchingType.name;
      }

      // 尝试从旧的字典中查找
      const found = this.dict.type.product_type.find(d => d.value === typeId || d.value === typeStr);
      if (found) return found.label;

      // 如果仍找不到，返回ID信息
      return `类型(${typeId})`;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 取消收藏 */
    cancelCollection(id) {
      this.$confirm('确定要取消收藏该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        toggleBookmark(id).then(response => {
          this.$message.success('取消收藏成功');
          this.getList(); // 刷新列表
        }).catch(error => {
          this.$message.error('操作失败：' + (error.msg || '未知错误'));
        });
      }).catch(() => {
        // 用户取消操作，不做处理
      });
    },
    viewProduct(item) {
      // 使用 Vue Router 跳转到商品详情页面
      this.$router.push({name: 'ProductDetail', params: {productId: item.id}});
    },
    // 处理分页变化
    handlePagination(val) {
      this.queryParams.pageNum = val.page;
      this.queryParams.pageSize = val.limit;
      this.getList();
    },
    // 跳转到商品列表页
    goToProductList() {
      this.$router.push({ name: 'ProductList' });
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  /* 级联选择器样式 */
  ::v-deep .el-cascader {
    width: 100% !important;

    .el-input__inner {
      height: 32px;
      line-height: 32px;
      padding-right: 30px;
    }

    .el-input__suffix {
      right: 5px;
      top: 1px;
      pointer-events: auto;
    }

    .el-cascader__dropdown {
      z-index: 3000 !important; /* 确保级联下拉框在最顶层 */
    }
  }

  /* 确保下拉菜单可见 */
  ::v-deep .el-select-dropdown, ::v-deep .el-cascader-menus {
    z-index: 3000 !important;
    visibility: visible !important;
    display: block !important;
    position: absolute !important;
    opacity: 1 !important;
  }

  .page-header {
    margin-bottom: 20px;

    .header-title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8px;

      i {
        color: #F56C6C; /* 使用红色图标表示收藏 */
        margin-right: 10px;
        font-size: 24px;
      }
    }

    .header-desc {
      color: #606266;
      font-size: 14px;
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  .product-list-card {
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .header-actions {
        .el-button {
          color: #606266;

          i.el-icon--right {
            margin-left: 5px;
          }
        }
      }
    }
  }

  .products-container {
    .product-col {
      margin-bottom: 20px;

      .product-card {
        height: 100%;
        transition: all 0.3s;
        border-radius: 6px;
        overflow: hidden;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        background-color: #fff;
        border: 1px solid #ebeef5;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
        }

        .product-image {
          height: 160px;
          overflow: hidden;
          position: relative; /* 设置为相对定位，为绝对定位的子元素提供定位上下文 */
        }

        .product-image img {
          width: 100%;
          height: 100%;
          object-fit: cover; /* 保证图片覆盖整个容器 */
          transition: transform 0.6s; /* 添加过渡效果，使图片缩放时有动画效果 */
        }

        .product-image:hover img {
          transform: scale(1.05); /* 鼠标悬停时图片放大 */
        }

        .product-image .product-tags {
          position: absolute; /* 设置为绝对定位，使其脱离文档流 */
          top: 8px; /* 距离容器顶部8像素 */
          right: 8px; /* 距离容器右侧8像素 */
          z-index: 2; /* 确保标签在图片上方显示 */
        }

        .product-info {
          padding: 12px;
          background: #fff;

          .product-title {
            font-size: 14px;
            margin-bottom: 8px;
            line-height: 1.4;
            height: 40px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            color: #303133;
            font-weight: 500;
          }

          .product-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 10px;
            font-size: 12px;

            .product-type, .product-supplier {
              color: #909399;
              background: #f5f7fa;
              padding: 2px 6px;
              border-radius: 3px;
              display: inline-block;
              max-width: 100%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .bottom-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .product-price {
              color: #f56c6c;
              font-size: 16px;
              font-weight: bold;
            }
          }
        }
      }
    }

    .empty-block {
      padding: 40px 0;
      text-align: center;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 15px;
        display: block;
        color: #F56C6C; /* 使用红色图标 */
      }

      span {
        display: block;
        margin-bottom: 15px;
      }
    }
  }

  .pagination-container {
    text-align: right;
    padding-top: 20px;
  }
}

@media screen and (max-width: 1200px) {
  .products-container .product-col {
    width: 25%;
  }
}

@media screen and (max-width: 992px) {
  .products-container .product-col {
    width: 33.33%;
  }
}

@media screen and (max-width: 768px) {
  .products-container .product-col {
    width: 50%;
    padding: 0 8px;
    margin-bottom: 16px;
  }

  .app-container {
    padding: 15px;
  }

  .products-containers .product-card .product-image {
    height: 140px;
  }
}

@media screen and (max-width: 480px) {
  .products-container .product-col {
    width: 100%;
    padding: 0 5px;
    margin-bottom: 15px;
  }
}
</style>

<style lang="scss">
/* 防止下拉框自动展开 */
.el-select-dropdown.el-popper {
  display: none;
}
.el-select-dropdown.el-popper[style*="display: block"] {
  display: block !important;
}
</style>
